package com.example.mychat.Utils.Filter;

import com.alibaba.fastjson.JSONObject;
import com.example.mychat.Pojo.Result;
import com.example.mychat.Utils.JWT;
import com.fasterxml.jackson.databind.util.JSONPObject;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;


@Component
@Slf4j
/**
 * 默认拦截所有请求
 */
@WebFilter(urlPatterns = "/*")
public class FilterIndex implements Filter {

    /**
     * 初始化过滤器时调用
     *
     * @param filterConfig 加载过滤器配置信息
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 主要方法体，决定请求的拦截与放行
     *
     * @param servletRequest  请求地址信息
     * @param servletResponse 响应信息
     * @param filterChain     过滤器链
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        先来个强制类型转化
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        获取url地址
        String url = request.getRequestURL().toString();
        log.info("请求的url:" + url);

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            log.info("options请求直接放行");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
//判断是否是登录或注册请求
        if (url.contains("login") || url.contains("signup")) {
            log.info("登录或注册请求,放行！");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
//如果不是则获取jwt令牌

        String jwt="12";
        if(url.contains("Websocket")){
            jwt= request.getParameter("token");
        }else{
            log.info("test");
            jwt = request.getHeader("Authorization");
        }
        log.info("拦截器获取到jwt令牌{}", jwt);
        if (!StringUtils.hasLength(jwt)) {
            log.info("token为空");
            Result error = Result.error("token未找到");
            String notLogin = JSONObject.toJSONString(error);
            /**
             * 这个一旦响应体被写入数据就会自动返回给前端
             */
            response.getWriter().write(notLogin);
            return;
        }
        try{
            JWT.parseJWT(jwt);
            log.info("解析成功");
        }catch(Exception e){
            e.printStackTrace();
            log.info("解析失败");
            Result error=Result.error("登陆过期，请重新登录！");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("资源已释放:过滤器销毁");
    }
}
